package com.chinaums.xm.wechat.service.wechat;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Optional;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.chinaums.xm.wechat.WeixinConstant;
import com.chinaums.xm.wechat.domain.wechat.AccessToken;
import com.chinaums.xm.wechat.domain.wechat.menu.BaseButton;
import com.chinaums.xm.wechat.domain.wechat.menu.Button;
import com.chinaums.xm.wechat.domain.wechat.menu.ClickButton;
import com.chinaums.xm.wechat.domain.wechat.menu.IndividuationMenu;
import com.chinaums.xm.wechat.domain.wechat.menu.Matchrule;
import com.chinaums.xm.wechat.domain.wechat.menu.Menu;
import com.chinaums.xm.wechat.domain.wechat.menu.ViewButton;
import com.chinaums.xm.wechat.service.Communicator;

import net.sf.json.JSONObject;
/**
 * 自定义菜单service
 * @author chenjf
 *
 */
@Service
public class MenuService {

	@Resource
	private CommonService commonService;
	
	@Resource
	private Communicator communicator;
	
	/**
	 * 创建个性化菜单
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public boolean createIndividuationMenu() throws UnsupportedEncodingException{
		boolean result = false;
		final Optional<AccessToken> accessToken = commonService.getAccessToken();
		if(accessToken.isPresent()){
			final String menuUrl = WeixinConstant.INDIVIDUATION_MENU_CREATE_URL.replace("ACCESS_TOKEN", accessToken.get().getToken());
			final ClickButton button1 = new ClickButton(); // 第一个Click按钮菜单
			button1.setName("菜单1");
			button1.setType("click");
			button1.setKey("button1");
			final ViewButton button2 = new ViewButton(); // 第二个View按钮菜单
			button2.setName("菜单2");
			button2.setType("view");
			final String url = String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect",
                    WeixinConstant.APP_ID, URLEncoder.encode("http://5f156484.ngrok.io/wechat/getUserInfo","utf-8"), "snsapi_userinfo", "123");
			button2.setUrl(url);
			final Button button5 = new Button(); // 第三个菜单
//			final ClickButton button3 = new ClickButton(); // 第三个菜单的第一个子菜单Click按钮
//			button3.setName("子菜单1");
//			button3.setType("click");
//			button3.setKey("button3");
			final ViewButton button4 = new ViewButton(); // 第三个菜单的第二个子菜单View按钮
			button4.setName("子菜单2");
			button4.setType("view");
			button4.setUrl("http://www.baidu.com");
			button5.setSub_button(new BaseButton[]{button4});
			button5.setName("菜单3");
			final IndividuationMenu menu = new IndividuationMenu(); // 菜单
			menu.setButton(new BaseButton[]{button1,button2,button5});
			Matchrule matchrule = new Matchrule();
			matchrule.setTag_id("100");
			menu.setMatchrule(matchrule);
			final JSONObject jSONObject = JSONObject.fromObject(menu);
			final Optional<String> responseMsg = communicator.postRequest(menuUrl, String.valueOf(jSONObject));
			if(responseMsg.isPresent()){
//				468449443
				final JSONObject response = JSONObject.fromObject(responseMsg.get());
				final String errCode = response.getString("errcode");
				if(errCode.equals("0")){
					result = true;
				}
			}
		}
		return result;
	}
	
	/**
	 * 创建菜单
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public boolean createMenu() throws UnsupportedEncodingException{
		boolean result = false;
		final Optional<AccessToken> accessToken = commonService.getAccessToken();
		if(accessToken.isPresent()){
			final String menuUrl = WeixinConstant.MENU_CREATE_URL.replace("ACCESS_TOKEN", accessToken.get().getToken());
			final ClickButton button1 = new ClickButton(); // 第一个Click按钮菜单
			button1.setName("菜单1");
			button1.setType("click");
			button1.setKey("button1");
			final ViewButton button2 = new ViewButton(); // 第二个View按钮菜单
			button2.setName("菜单2");
			button2.setType("view");
			final String url = String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect",
                    WeixinConstant.APP_ID, URLEncoder.encode("http://5f156484.ngrok.io/wechat/getUserInfo","utf-8"), "snsapi_userinfo", "123");
			button2.setUrl(url);
			final Button button5 = new Button(); // 第三个菜单
			final ClickButton button3 = new ClickButton(); // 第三个菜单的第一个子菜单Click按钮
			button3.setName("子菜单1");
			button3.setType("click");
			button3.setKey("button3");
			final ViewButton button4 = new ViewButton(); // 第三个菜单的第二个子菜单View按钮
			button4.setName("子菜单2");
			button4.setType("view");
			button4.setUrl("http://www.baidu.com");
			button5.setSub_button(new BaseButton[]{button3,button4});
			button5.setName("菜单3");
			final Menu menu = new Menu(); // 菜单
			menu.setButton(new BaseButton[]{button1,button2,button5});
			final JSONObject jSONObject = JSONObject.fromObject(menu);
			final Optional<String> responseMsg = communicator.postRequest(menuUrl, String.valueOf(jSONObject));
			if(responseMsg.isPresent()){
				final JSONObject response = JSONObject.fromObject(responseMsg.get());
				final String errCode = response.getString("errcode");
				if(errCode.equals("0")){
					result = true;
				}
			}
		}
		return result;
	}
	
	/**
	 * 个性化菜单查询
	 */
	public void queryIndividuationMenu(){
		final Optional<AccessToken> accessToken = commonService.getAccessToken();
		final String menuQueryUrl = WeixinConstant.TRYMATCH_INDIVIDUATION_MENU_CREATE_URL.replace("ACCESS_TOKEN", accessToken.get().getToken());
		final JSONObject jSONObject = JSONObject.fromObject("{\"user_id\":\"CJF646518874\"}");
		final Optional<String> responseMsg = communicator.postRequest(menuQueryUrl, String.valueOf(jSONObject));
		if(responseMsg.isPresent()){
			final JSONObject response = JSONObject.fromObject(responseMsg.get());
			System.out.println(response);
		}
	}
	
	/**
	 * 菜单查询
	 */
	public void queryMenu(){
		final Optional<AccessToken> accessToken = commonService.getAccessToken();
		final String menuQueryUrl = WeixinConstant.MENU_QUERY_URL.replace("ACCESS_TOKEN", accessToken.get().getToken());
		final Optional<String> repsonseMsg = communicator.getRequest(menuQueryUrl);
		if(repsonseMsg.isPresent()){
			final String response = repsonseMsg.get();
			System.out.println(response);
		}
	}
	
	/**
	 * 菜单删除
	 */
	public boolean deleteMenu(){
		boolean result = false;
		final Optional<AccessToken> accessToken = commonService.getAccessToken();
		final String menuQueryUrl = WeixinConstant.MENU_DELETE_URL.replace("ACCESS_TOKEN", accessToken.get().getToken());
		final Optional<String> repsonseMsg = communicator.getRequest(menuQueryUrl);
		if(repsonseMsg.isPresent()){
			final String response = repsonseMsg.get();
			final JSONObject json = JSONObject.fromObject(response);
			final String errcode = json.getString("errcode");
			if(errcode.equals("0")){
				result = true;
			}
		}
		return result;
	}
	
	/**
	 * 获取自定义菜单配置接口
	 * 本接口将会提供公众号当前使用的自定义菜单的配置，如果公众号是通过API调用设置的菜单，则返回菜单的开发配置，
	 * 而如果公众号是在公众平台官网通过网站功能发布菜单，则本接口返回运营者设置的菜单配置。
	 */
	public void queryMenuSetting(){
		final Optional<AccessToken> accessToken = commonService.getAccessToken();
		final String menuSettingQueryUrl = WeixinConstant.MENU_SETTING_QUERY_URL.replace("ACCESS_TOKEN", accessToken.get().getToken());
		final Optional<String> repsonseMsg = communicator.getRequest(menuSettingQueryUrl);
		if(repsonseMsg.isPresent()){
			final String response = repsonseMsg.get();
			System.out.println(response);
		}
	}
}
